import axios from "axios"

function fetch(base = 'VITE_BASE_URL') {
  // 配置请求baseurl
  const instance = axios.create({ baseURL: base ? import.meta.env[base] : '', timeout: 600000 })

  instance.interceptors.request.use((config) => {
    return config
  }, (error) => {
    return Promise.reject(error)
  })

  return {
    get(url, params) {
      let data = {
        method: "get",
        url,
        params,
        headers: {
          "Content-type": "application/json",
        }
      }
      return instance(data).then(res => {
        return res.data
      })
    },
    authGet(url, params) {
      let user_id = window.localStorage.getItem("user_id") ? window.localStorage.getItem("user_id") : ""
      let auth_token = window.localStorage.getItem("auth_token") ? window.localStorage.getItem("auth_token") : ""
      let data = {
        method: "get",
        url,
        params,
        headers: {
          "Content-type": "application/json",
          "userid": user_id,
          "token": auth_token
        }
      }
      return instance(data).then(res => {
        return res.data
      })
    },
    post(url, params) {
      let user_id = window.localStorage.getItem("user_id") ? window.localStorage.getItem("user_id") : ""
      let auth_token = window.localStorage.getItem("auth_token") ? window.localStorage.getItem("auth_token") : ""
      let data = {
        method: "post",
        url,
        data: params,
        headers: {
          "userid": user_id,
          "token": auth_token,
          "Content-type": "application/json",
          "X-Requested-With": "xmlhttprequest"
        }
      }
      return instance(data).then(res => {
        return res.data
      })
    },
    formData(url, params) {
      let data = {
        method: "post",
        url,
        data: params,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        transformRequest: [function (params) {
          let ret = ""
          for (let key in params) {
            ret += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&"
          }
          return ret
        }]
      }
      return instance(data).then(res => {
        return res.data
      })
    },
    postFiles(url, params) {
      console.log(params, 'params')
      let data = {
        method: "post",
        url,
        data: params,
        headers: {
          "Content-Type": "multipart/form-data",
          "token": ""
        }
      }
      return instance(data).then(res => {
        return res
      })
    }
  }

}
export const { get, authGet, post, formData, postFiles } = fetch()
export default fetch